package com.party.controller.user.exam;

import com.party.common.Tools;
import com.party.model.*;
import com.party.service.exam.ExamService;
import com.party.service.exam.ExamTestService;
import com.party.service.exam.User2ExamService;
import com.party.service.exam.User2ExamTestService;
import com.party.service.news.NewsService;
import com.party.service.study.CurriculumService;
import com.party.service.study.LearningContentService;
import com.party.service.study.TestService;
import com.party.service.study.User2TestService;
import com.sun.deploy.net.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: beyond
 * Date: 14-10-8
 * Time: 下午10:27
 * To change this template use File | Settings | File Templates.
 */

@Controller
@RequestMapping(value = "/exam")
public class ExamController {

    @Resource
    ExamService examService;
    @Resource
    CurriculumService curriculumService;
    @Resource
    LearningContentService learningContentService;
    @Resource
    User2TestService user2TestService;
    @Resource
    TestService testService;
    @Resource
    ExamTestService examTestService;
    @Resource
    User2ExamService user2ExamService;

    @Resource
    User2ExamTestService user2ExamTestService;
    private int perNum = 5;//每次传给前端的题目数

    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "startCurrTest")
    public ModelAndView startCurrTest(HttpServletRequest request,HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        String idStr = request.getParameter("id");
        List<Test> testList = new ArrayList<Test>();//传给前端的考试题目（）
        int realSumNum  = 0;//考试的总题目数
        int preScore = 0;
        int time = 0;
        if ( session.getAttribute("sysUser") != null) {
            SysUser user = (SysUser) session.getAttribute("sysUser");
            modelAndView.addObject("realName",user.getRealname());
            modelAndView.addObject("passport",user.getPassport());
            if(Tools.isNumber(idStr))
            {
                //判断该考试是否已经考试过
                List<Curriculum> curriculums = this.curriculumService.getByUidOld(user.getUid());
                if(curriculums != null && curriculums.size() >0)
                {
                    for(Curriculum curriculum:curriculums)
                    {
                        //已经考过了
                        if(curriculum.getId() == Integer.parseInt(idStr))
                        {
                            modelAndView.setViewName("redirect:/test/testList.do");
                            return modelAndView;
                        }
                    }
                }

                Integer id = Integer.parseInt(idStr);
                Curriculum curr = curriculumService.getById(id);
                time = curr.getTesttime();
                int testNum = curr.getTestnum();//题目数量
                int maxNum = 0;//这个课程下共有题目数
                List<LearningContent> contentList = this.learningContentService.getByCurrId(curr.getId());

                if(contentList != null && contentList.size() > 0)
                {
                    //找到所有题目 集合
                    List<Test> sumTestList = new ArrayList<Test>();
                    List<Test> resultTestList = new ArrayList<Test>();//接下来要考试的题目，存到session
                    for(LearningContent content:contentList)
                    {
                        List<Test> temp = this.testService.getByContentId(content.getId());
                        if(temp != null && temp.size() >0)
                        {
                            sumTestList.addAll(temp);
                            maxNum = maxNum + temp.size();
                        }
                    }
                    //如果数据库的题目都不够，就所有的题目都用上，不用随机出题了
                    if(testNum < maxNum)
                    {
                        //随机数
                        List<Integer> indexList = Tools.getRandom(testNum,0,(maxNum-1));
                        for(Integer index:indexList)
                        {
                            resultTestList.add(sumTestList.get(index));
                        }
                    }
                    else
                    {
                        resultTestList = sumTestList;
                    }
                    realSumNum = resultTestList.size();
                    preScore = curr.getScore()/realSumNum;
                    for(int i= 0; i<resultTestList.size(); i++)
                    {
                        //前几道题直接发到前端
                        //剩下来的存到session
                        if(i<perNum)
                        {
                            testList.add(sumTestList.get(i));
                        }
                        else
                        {
                            break;
                        }
                    }
                    resultTestList.removeAll(testList);//移除已经发送的
                    //将本次考试的题目存到session
                    session.setAttribute("testList",resultTestList);
                    session.setAttribute("testIndex",testList.size());//设置当前的题目到多少号了
                }
            }
        }
        else
        {
            modelAndView.setViewName("/login");
            return modelAndView;
        }

        modelAndView.addObject("testList",testList);
        modelAndView.addObject("num",realSumNum);//题目总数
        modelAndView.addObject("preMin",1);//当前题目最小
        modelAndView.addObject("preMax",testList.size());//当前题目最大
        modelAndView.addObject("id",idStr);//课程id
        modelAndView.addObject("time",time);//时间
        modelAndView.addObject("preScore",preScore);//每题答对的得分
        modelAndView.setViewName("/user/exam/learningExam");
        return modelAndView;
    }
    /**
     * 下一页
     * @param request
     * @return
     */
    @RequestMapping(value = "testNext")
    @ResponseBody
    public Map<String,Object> testNext(HttpServletRequest request, HttpSession session) {
        Map<String,Object> map = new HashMap<String, Object>();
        String currIdStr = request.getParameter("id");
        String preScoreStr = request.getParameter("preScore");//每题答对的的得分
        int preScore = 1;
        if(Tools.isNumber(preScoreStr))
        {
            preScore = Integer.parseInt(preScoreStr);
        }
        String nameListStr = request.getParameter("nameList");
        if ( session.getAttribute("sysUser") != null) {
            Integer uid = ((SysUser) session.getAttribute("sysUser")).getUid();
            if(nameListStr != null && !("").equals(nameListStr) && Tools.isNumber(currIdStr))
            {
                List<User2Test> user2TestList = new ArrayList<User2Test>();
                Integer currId = Integer.parseInt(currIdStr);
                String[] nameList = nameListStr.split(",");
                for(String name:nameList)
                {
                    String[] values = request.getParameterValues(name);//选择的答案
                    String anIds = "";
                    if(values != null && !"".equals(values))
                    {
                        for(String v:values)
                        {
                            if(anIds.equals(""))
                            {
                                anIds = v;
                            }
                            else {
                                anIds = anIds+","+v;
                            }
                        }
                    }
                    else {
                        values = new String[]{};
                    }
                    User2Test user2Test = new User2Test();
                    user2Test.setUid(uid);
                    user2Test.setCurriculumid(currId);
                    user2Test.setTestid(Integer.parseInt(name));
                    user2Test.setAnswerids(anIds);
                    user2Test.setAnswerList(values);
                    user2TestList.add(user2Test);
                }
                this.user2TestService.add(user2TestList,preScore);
            }

            //处理往前端传数据
            if(session.getAttribute("testList") != null){
                List<Test> testList = (List<Test>)session.getAttribute("testList");
                if(testList.size() <=0)
                {
                    map.put("isFinish","1");//没有题目了
                }
                else
                {
                    map.put("isFinish","0");
                    Integer index = (Integer)session.getAttribute("testIndex");
                    List<Test> showList = new ArrayList<Test>();
                    if(testList.size() <= this.perNum)
                    {
                        showList = testList;
                        testList = new ArrayList<Test>();
                    }else
                    {
                        for(int i=0; i<this.perNum;i++)
                        {
                            Test test = testList.get(i);
                            showList.add(test);
                        }
                        testList.removeAll(showList);
                    }
                    session.setAttribute("testList",testList);
                    session.setAttribute("testIndex",(index+showList.size()));
                    map.put("preMin",(index+1));
                    map.put("preMax",(index+showList.size()));
                    map.put("testList",showList);
                }
            }
        }
        return map;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value = "startExamTest")
    public ModelAndView startExamTest(HttpServletRequest request,HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        String idStr = request.getParameter("id");
        List<ExamTest> testList = new ArrayList<ExamTest>();//传给前端的考试题目（）
        int realSumNum  = 0;//考试的总题目数
        int preScore = 0;
        int time = 0;
        if ( session.getAttribute("sysUser") != null) {
            SysUser user = (SysUser) session.getAttribute("sysUser");
            modelAndView.addObject("realName",user.getRealname());
            modelAndView.addObject("passport",user.getPassport());
            if(Tools.isNumber(idStr))
            {
                //判断该考试是否已经考试过
                List<Exam> exams = this.examService.getByUid(user.getUid());
                if(exams != null && exams.size() >0)
                {
                    for(Exam exam:exams)
                    {
                        //已经考过了
                        if(exam.getId() == Integer.parseInt(idStr))
                        {
                            modelAndView.setViewName("redirect:/test/testList.do");
                            return modelAndView;
                        }
                    }
                }
                Integer id = Integer.parseInt(idStr);
                Exam exam = examService.getExamByPrimaryKey(id);

                //////////保存考试user2exam
                User2Exam user2Exam = new User2Exam();
                user2Exam.setUid(user.getUid());
                user2Exam.setMaxscore(exam.getScore());
                user2Exam.setExamid(exam.getId());
                this.user2ExamService.add(user2Exam);
                /////////

                time = exam.getTesttime();
                int testNum = exam.getTestnum();//题目数量
                int maxNum = 0;//这个课程下共有题目数
                List<ExamTest> tempList = new ArrayList<ExamTest>();
                List<ExamTest> examTestList = this.examTestService.getByExamId(id);
                if(examTestList != null)
                {
                    //如果数据库的题目都不够，就所有的题目都用上，不用随机出题了
                    if(examTestList.size() <= testNum)
                    {
                        tempList = examTestList;
                    }
                }
                else
                {
                    //随机数
                    List<Integer> indexList = Tools.getRandom(testNum,0,(examTestList.size()-1));
                    for(Integer index:indexList)
                    {
                        tempList.add(examTestList.get(index));
                    }
                }
                realSumNum =tempList.size();
                preScore = exam.getScore()/realSumNum;
                if(tempList.size() <= perNum)
                {
                    testList = tempList;
                    tempList = new ArrayList<ExamTest>();
                }
                else{
                    for(int i=0;i<this.perNum;i++)
                    {
                        testList.add(tempList.get(i));
                    }
                    tempList.removeAll(testList);
                }
                session.setAttribute("testList",tempList);
                session.setAttribute("testIndex",testList.size());//设置当前的题目到多少号了
            }
        }
        else
        {
            modelAndView.setViewName("/login");
            return modelAndView;
        }

        modelAndView.addObject("testList",testList);
        modelAndView.addObject("num",realSumNum);//题目总数
        modelAndView.addObject("preMin",1);//当前题目最小
        modelAndView.addObject("preMax",testList.size());//当前题目最大
        modelAndView.addObject("id",idStr);//examid
        modelAndView.addObject("time",time);//时间
        modelAndView.addObject("preScore",preScore);//每题答对的得分
        modelAndView.setViewName("/user/exam/exam");
        return modelAndView;
    }

    /**
     * 下一页
     * @param request
     * @return
     */
    @RequestMapping(value = "examTestNext")
    @ResponseBody
    public Map<String,Object> examTestNext(HttpServletRequest request, HttpSession session) {
        Map<String,Object> map = new HashMap<String, Object>();
        String examIdStr = request.getParameter("id");
        String preScoreStr = request.getParameter("preScore");//每题答对的的得分
        int preScore = 1;
        if(Tools.isNumber(preScoreStr))
        {
            preScore = Integer.parseInt(preScoreStr);
        }
        String nameListStr = request.getParameter("nameList");
        if ( session.getAttribute("sysUser") != null) {
            Integer uid = ((SysUser) session.getAttribute("sysUser")).getUid();
            if(nameListStr != null && !("").equals(nameListStr) && Tools.isNumber(examIdStr))
            {
                List<User2Examtest> user2TestList = new ArrayList<User2Examtest>();
                Integer examId = Integer.parseInt(examIdStr);
                String[] nameList = nameListStr.split(",");
                for(String name:nameList)
                {
                    String[] values = request.getParameterValues(name);//选择的答案
                    String anIds = "";
                    if(values != null && !"".equals(values))
                    {
                        for(String v:values)
                        {
                            if(anIds.equals(""))
                            {
                                anIds = v;
                            }
                            else {
                                anIds = anIds+","+v;
                            }
                        }
                    }
                    else {
                        values = new String[]{};
                    }

                    User2Examtest user2Examtest = new User2Examtest();
                    user2Examtest.setUid(uid);
                    user2Examtest.setExamid(examId);
                    user2Examtest.setExamanswerids(anIds);
                    user2Examtest.setExamtestid(Integer.parseInt(name));
                    user2Examtest.setAnswerList(values);
                    user2TestList.add(user2Examtest);
                }
                this.user2ExamTestService.add(user2TestList,preScore);
            }

            //处理往前端传数据
            if(session.getAttribute("testList") != null){
                List<Test> testList = (List<Test>)session.getAttribute("testList");
                if(testList.size() <=0)
                {
                    map.put("isFinish","1");//没有题目了
                }
                else
                {
                    map.put("isFinish","0");
                    Integer index = (Integer)session.getAttribute("testIndex");
                    List<Test> showList = new ArrayList<Test>();
                    if(testList.size() <= this.perNum)
                    {
                        showList = testList;
                        testList = new ArrayList<Test>();
                    }else
                    {
                        for(int i=0; i<this.perNum;i++)
                        {
                            Test test = testList.get(i);
                            showList.add(test);
                        }
                        testList.removeAll(showList);
                    }
                    session.setAttribute("testList",testList);
                    session.setAttribute("testIndex",(index+showList.size()));
                    map.put("preMin",(index+1));
                    map.put("preMax",(index+showList.size()));
                    map.put("testList",showList);
                }
            }
        }
        return map;
    }

}
